<?php
/**
 * Created by PhpStorm.
 * User: rocky
 * Date: 2022-03-17
 * Time: 22:17
 */

namespace plugin\thinkphp\controller;

use plugin\thinkphp\Admin;
use ExAdmin\ui\component\common\Html;
use ExAdmin\ui\component\form\Form;
use ExAdmin\ui\component\grid\badge\Badge;
use ExAdmin\ui\component\grid\grid\Actions;
use ExAdmin\ui\component\grid\grid\Filter;
use ExAdmin\ui\component\grid\grid\Grid;
use think\db\Query;


/**
 * 系统用户管理
 */
class AdminController
{
    protected $model;

    public function __construct()
    {
        $this->model = plugin()->thinkphp->config('database.user_model');

    }

    /**
     * 系统用户
     * @auth true
     */
    public function index(): Grid
    {
        return Grid::create(new $this->model,function (Grid $grid){
            $grid->title(admin_trans('admin.system_user'));
            $grid->model()
                ->when(plugin()->thinkphp->config('admin_auth_id') != Admin::id(),function(Query $query){
                    $query->where('id','<>',plugin()->thinkphp->config('admin_auth_id'));
                })
                ->order('id','desc');
            $grid->userInfo();
            $grid->column('username', admin_trans('admin.fields.username'))->display(function ($val, $data) {
                if ($data['id'] == plugin()->thinkphp->config('admin_auth_id')) {
                    return Html::create()
                        ->content($val)
                        ->content(
                            Badge::create()->count(admin_trans('admin.super_admin'))->numberStyle(['backgroundColor' => '#1890ff', 'marginLeft' => '5px'])
                        );
                } else {
                    return $val;
                }
            });
            $grid->column('phone', admin_trans('admin.fields.phone'));
            $grid->column('email', admin_trans('admin.fields.mail'));
            $grid->column('status', admin_trans('admin.fields.status'))->switch();
            $grid->column('create_time', admin_trans('admin.fields.create_at'));
            $grid->quickSearch();
            $grid->hideDelete();
            $grid->setForm()->modal($this->form());
            $grid->filter(function (Filter $filter) {
                $filter->like()->text('username', admin_trans('admin.fields.username'));
                $filter->like()->text('phone', admin_trans('admin.fields.phone'));
                $filter->eq()->select('status', admin_trans('admin.fields.status'))->options([
                    1 => admin_trans('admin.normal'),
                    0 => admin_trans('admin.disable')
                ]);
                $filter->between()->dateRange('create_time', admin_trans('admin.fields.create_at'));
            });

            $department_model = plugin()->thinkphp->config('database.department_model');
            $grid->sidebar('department_id',new $department_model)
                ->tree()
                ->searchPlaceholder('搜索部门');

            $grid->actions(function (Actions $actions, $data) {
                if ($data['id'] == plugin()->thinkphp->config('admin_auth_id')) {
                    $actions->hideDel();
                }
                $actions->dropdown()
                    ->prepend(admin_trans('admin.reset_password'), 'fas fa-key')
                    ->modal($this->resetPassword($data['id']));

            });

            $grid->deling(function ($ids){
                if (is_array($ids) && in_array(plugin()->thinkphp->config('admin_auth_id'), $ids)) {
                    return message_error(admin_trans('admin.super_admin_delete'));
                }
            });

            $grid->updateing(function ($ids, $data){
                if (in_array(plugin()->thinkphp->config('admin_auth_id'), $ids)) {
                    if (isset($data['status']) && $data['status'] == 0) {
                        return message_error(admin_trans('admin.super_admin_disabled'));
                    }
                }
            });
        });
    }

    /**
     * 系统用户
     * @auth true
     */
    public function form(): Form
    {
        return Form::create(new $this->model,function (Form $form){
            $form->title(admin_trans('admin.system_user'));
            $form->text('username', admin_trans('admin.fields.username'))
                ->ruleChsDash()
                ->rule([
                    'unique:'.plugin()->thinkphp->config('database.user_model')=>admin_trans('admin.username_exist'),
                ])
                ->required()
                ->disabled($form->isEdit());
            $form->text('nickname', admin_trans('admin.fields.nickname'))
                ->ruleChsAlphaNum()
                ->required();
            $form->image('avatar', admin_trans('admin.fields.avatar'))
                ->required();
            if (!$form->isEdit()) {
                $form->password('password', admin_trans('admin.fields.password'))
                    ->default(123456)
                    ->help('初始化密码123456,建议密码包含大小写字母、数字、符号')
                    ->required();
            }
            $form->text('phone', admin_trans('admin.fields.phone'))
                ->rule([
                    'unique:'.plugin()->thinkphp->config('database.user_model')=> admin_trans('admin.phone_exist')
                ])
                ->ruleMobile();
            $form->text('email', admin_trans('admin.fields.mail'))->ruleEmail();
            if ($form->input('id') != plugin()->thinkphp->config('admin_auth_id')) {
                $roleModel = plugin()->thinkphp->config('database.role_model');
                $role = $roleModel::column('name', 'id');
                $form->checkbox('roles', admin_trans('admin.access_rights'))
                    ->options($role);

            }
            $department = plugin()->thinkphp->config('database.department_model');
            $options = $department::where('status',1)->select()->toArray();
            $form->treeSelect('department_id','所属部门')
                ->required()
                ->options($options);
            $department = plugin()->thinkphp->config('database.post_model');
            $options = $department::where('status',1)->column('name','id');
            $form->select('post','岗位')
                ->options($options)
                ->multiple();
        });
    }
    /**
     * 修改密码
     * @auth true
     * @return Form
     */
    public function updatePassword()
    {
        return Form::create(new $this->model,function (Form $form){
            $form->password('old_password', admin_trans('admin.old_password'))->required();
            $form->password('password', admin_trans('admin.new_password'))
                ->rule([
                    'confirm' => admin_trans('admin.password_confim_validate'),
                    'min:6' => admin_trans('admin.password_min_number')
                ])
                ->value('')
                ->required();
            $form->password('password_confirm', admin_trans('admin.confim_password'))
                ->required();
            $form->saving(function (Form  $form){
                if(!password_verify($form->input('old_password'),Admin::user()->password)){
                    return message_error(admin_trans('admin.old_password_error'));
                }
            });
        });
    }
    /**
     * 编辑个人信息
     * @auth true
     * @return Form
     */
    public function editInfo(){
        return Form::create(new $this->model,function (Form $form){
            $form->text('username', admin_trans('admin.fields.username'))
                ->ruleChsDash()->disabled();
            $form->text('nickname', admin_trans('admin.fields.nickname'))
                ->ruleChsAlphaNum();
            $form->image('avatar', admin_trans('admin.fields.avatar'));
            $form->text('phone', admin_trans('admin.fields.phone'))
                ->rule([
                    'unique:'.plugin()->thinkphp->config('database.user_model')=>admin_trans('admin.phone_exist')
                ])
                ->ruleMobile();
            $form->text('email', admin_trans('admin.fields.mail'))->ruleEmail();
        });
    }
    /**
     * 重置密码
     * @auth true
     * @param $id
     * @return Form
     */
    public function resetPassword($id)
    {
        return Form::create(new $this->model,function (Form $form){
            $form->password('password', admin_trans('admin.new_password'))
                ->rule([
                    'confirm' => admin_trans('admin.password_confim_validate'),
                    'min:6' => admin_trans('admin.password_min_number')
                ])
                ->value('')
                ->required();
            $form->password('password_confirm', admin_trans('admin.confim_password'))
                ->required();
        });
    }
}
